package com.longcai.cm.auth;

import com.longcai.cm.auth.token.LoginUserInfo;
import com.longcai.cm.auth.token.RequestUtil;
import com.longcai.cm.exception.SysRuntimeException;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限(Token)验证
 *
 * @author libingxing
 */
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    static final String USER_KEY = "username";

    static final String TOKEN = "token";

    @Override
    public boolean preHandle(
            @NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler
    ) {
        Login annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        } else {
            return true;
        }

        if (annotation == null) {
            return true;
        }

        // 获取用户凭证
        LoginUserInfo userInfo = RequestUtil.getUserInfoByRequest(request);

        // 凭证为空
        if (StringUtils.isEmpty(userInfo.getUserId())) {
            throw new SysRuntimeException("登录失效，请重新登录", HttpStatus.UNAUTHORIZED.value());
        }

        if (userInfo.getUserId() == null) {
            throw new SysRuntimeException("登录失效，请重新登录", HttpStatus.UNAUTHORIZED.value());
        }


        // 设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(USER_KEY, userInfo.getUserId());
        request.setAttribute(TOKEN, request.getHeader(TOKEN));

        return true;
    }
}
